package com.lyc.mall.controller.admin;

import com.google.gson.Gson;
import com.lyc.mall.model.BO.OrdersByPageBO;
import com.lyc.mall.model.VO.OrdersByPageVO;
import com.lyc.mall.service.OrderService;
import com.lyc.mall.service.impl.OrderServiceImpl;
import com.lyc.mall.util.HttpUtils;
import com.lyc.mall.util.Result;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/api/admin/order/*")
public class OrderServlet extends HttpServlet {
    Gson gson = new Gson();

    private OrderService orderService = new OrderServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String operation = HttpUtils.getOperation(req);
        if ("ordersByPage".equals(operation)) {
            ordersByPage(req, resp);
        }
    }

    /**
     * 1、获取请求参数
     * 请求体中不是key=value形式，用自己的HttpUtils
     * 无论请求行还是请求体中的key=value，用request.getParameter()来获取
     * 2、处理业务逻辑
     * 3、返回参数
     *
     * @param req
     * @param resp
     */
    private void ordersByPage(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String requestBody = HttpUtils.getRequestBody(req);
        OrdersByPageBO ordersByPageBO = gson.fromJson(requestBody, OrdersByPageBO.class);
        // todo 判断pageSize和currentPage一定要传，且必须为数字
        // MoneyLimit可以不填，但填的话必须为数字
        try {
            // 金额下限
            if (!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit2())) {
                Double.parseDouble(ordersByPageBO.getMoneyLimit2());
            }
            // 金额上限
            if (!StringUtils.isEmpty(ordersByPageBO.getMoneyLimit1())) {
                Double.parseDouble(ordersByPageBO.getMoneyLimit1());
            }
        } catch (Exception e) {
            resp.getWriter().println(gson.toJson(Result.ERROR("金额不能为空")));
            return;
        }
        OrdersByPageVO ordersByPageVO = orderService.ordersByPage(ordersByPageBO);
        resp.getWriter().println(gson.toJson(Result.OK(ordersByPageVO)));
    }
}
